class Compiler {
  constructor (vm) {
    console.log(vm)
    this.el = vm.$el
    this.vm = vm
    this.compile(this.el)
  }
  compile (el) {
    let childNodes = el.childNodes
    Array.from(childNodes).forEach(node => {
      if (this.isTextNode(node)) {
        this.compileText(node)
      } else if (this.isElementNode(node)) {
        this.compileElement(node)
      }

      if (node.childNodes && node.childNodes.length) {
        this.compile(node)
      }
    })
  }
  compileElement (node) {
    Array.from(node.attributes).forEach(attr => {
      let attrName = attr.name
      if (this.isDirective(attrName)) {
        // v-text --> text
        attrName = attrName.substr(2)
        let key = attr.value
        this.update(node, key, attrName)
      }
    })
  }

  update (node, key, attrName) {
    // 判断是否为 v-on 指令
    if (attrName.startsWith('on:')) {
      // on:click --> click
      const eventName = attrName.substr(3)
      const $options = this.vm.$options || {}
      const methods = $options.methods || {}
      this.onUpdater.call(this, node, eventName, methods[key])
    } else {
      let updateFn = this[attrName + 'Updater']
      updateFn && updateFn.call(this, node, this.vm[key], key)
    }
  }

  // v-model
  modelUpdater (node, value, key) {
    node.value = value
    new Watcher(this.vm, key, (newValue) => {
      node.value = newValue
    })
    // 双向绑定
    node.addEventListener('input', () => {
      this.vm[key] = node.value
    })
  }
  // 处理 v-on 指令
  onUpdater (node, eventName, func) {
    console.log('触发 v-on')
    node.addEventListener(eventName, () => {
      func.call(this.vm)
    })
  }

  textUpdater (node, value, key) {
    node.textContent = value
    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue
    })
  }
  htmlUpdater (node, value, key) {
    node.innerHTML = value
    new Watcher(this.vm, key, (newValue) => {
      node.innerHTML = newValue
    })
  }
  
  compileText (node) {
    let reg = /\{\{(.+?)\}\}/
    let value = node.textContent
    if (reg.test(value)) {
      let key = RegExp.$1.trim()
      node.textContent = value.replace(reg, this.vm[key])

      new Watcher(this.vm, key, (newValue) => {
        node.textContent = newValue
      })
    }
  }
  isDirective (attrName) {
    return attrName.startsWith('v-')
  }
  isTextNode (node) {
    return node.nodeType === 3
  }
  isElementNode (node) {
    return node.nodeType === 1
  }
}